const ws = require('./ws');
const CONFIG = require(`${process.root}/config`)

// https://docs.go-cqhttp.org/
async function onMsg(data, callback, config = {}) {
  const { self_id, post_type, message_type = '', raw_message = '', user_id = 0, sender} = data;
  const { checkAdmin = true, checkAt = true, checkName = true } = config;
  // 过滤非消息
  if (post_type !== "message") return;
  if (!message_type) return;
  // 过滤非管理员
  if (checkAdmin && user_id !== CONFIG.bot.adminId) return;
  // 群聊通过 @bot 或 bot开头 触发
  if (message_type === 'group') {
    const { group_id = 0 } = data;
    // 检测群号是否允许运行 bot
    if (!CONFIG.bot.groups[group_id]) return;
    let temp;
    if (checkAt || checkName) {
      if (checkName && !temp) temp = raw_message.match(new RegExp(`(?<=${CONFIG.bot.nameList.map(name => `(${name})`).join('|')}\\s+?).+`, 'g'));
      if (checkAt && !temp) temp = raw_message.match(new RegExp(`(?<=\\[CQ:at,qq=${self_id}\\]\\s+?).+`, 'g'));
      if (!temp) return;
    }
    temp = [raw_message];
    const msg = temp[0];
    const params = await callback(msg, sender);
    if (!params) return;
    ws.send('send_group_msg', Object.assign({ group_id }, params));
    return;
  }
  // 私聊直接触发
  if (message_type === 'private') {
    const { user_id } = data;
    const params = await callback(raw_message, sender);
    if (!params) return;
    ws.send('send_private_msg', Object.assign({ user_id }, params));
    return;
  };
}

module.exports = onMsg;